﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using LibraryHub.Core.Models.User;

namespace LibraryHub.Core.Helpers
{
    public static class EnumHelper
    {
        public static string GetDescription(this Enum value)
        {
            FieldInfo field = value.GetType().GetField(value.ToString());
            //TODO: can throw exception if value is not one of known enums. Instead of catching exception here, should not allow enter invalid enum.
            DescriptionAttribute attribute
                = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
                  as DescriptionAttribute;

            return attribute == null ? value.ToString() : attribute.Description;
        }

        public static SelectList ToSelectList(this UserRoleEnum enumObj)
        {
            var values = from UserRoleEnum e in Enum.GetValues(typeof(UserRoleEnum))
                         select new { ID = (int)e, Name = e.GetDescription() };
            
            return new SelectList(values, "Id", "Name"); //TODO: Q: how do I set up SelectedItem?
        }

        public static SelectList ToSelectListWithEmptyItem(this UserRoleEnum enumObj)
        {
            var values = from UserRoleEnum e in Enum.GetValues(typeof(UserRoleEnum))
                         select new { ID = (int)e, Name = e.GetDescription() };
            var list = values.ToList();
            list.Insert(0, new { ID = 0, Name = "Не выбрано" }); //TODO: I was unable to set current item in DropDown/DelectList

            return new SelectList(list, "Id", "Name");
        }
    }
}